﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    /// <summary>
    /// RESPONSABILITY: - machine repository
    ///                 - create new machines
    ///                 - add machine to the list of machines
    ///                 - delete a machine
    /// </summary>
    public class ChangeMachine
    {
        private List<Machine> machines = new List<Machine>();
        public IEnumerable<Machine> GetMachines(List<string> codes = null)
        {
            if (codes == null)
            {
                return machines;
            }

            var result = machines.Where(c => codes.Contains(c.MachineCode));

            //Console.WriteLine("GetCompanies returns " + result.Count() + " results" );

            return result;
        }

        public Machine CreateMachine(string machineCode, string machineDescription,int costPerHour)
        {
            if (string.IsNullOrEmpty(machineCode))
            {
                throw new ArgumentException("The task cod cannot be null", machineCode);
            }

            Machine machine = new Machine(machineCode, machineDescription, costPerHour);
            this.AddMachine(machine);
            return machine;
        }

        public void AddMachine(Machine machine)
        {
            if (CheckMachineIDExistance(machine.MachineId))
            {
                return;
            }

            if (CheckMachineCodeExistance(machine.MachineCode))
            {
                throw new Exception("A machine with the code " + machine.MachineCode + " already exists");
            }

            machines.Add(machine);

        }

        private bool CheckMachineCodeExistance(string code)
        {
            var _machine = machines.FirstOrDefault(t => t.MachineCode == code);

            var isFound = _machine != null;

            return isFound;
        }

        private bool CheckMachineIDExistance(int id)
        {
            var _machine = machines.FirstOrDefault(e => e.MachineId == id);

            var isFound = _machine != null;

            return isFound;
        }

        public void DeleteMachine(Machine machine)
        {
           Machine removeMachine = machines.FirstOrDefault(t => t.MachineId == machine.MachineId);
            if (removeMachine != null)
            {
                machines.Remove(machine);
            }
        }
    }
}
